package com.ruoyi.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.ruoyi.article.api.domain.ApArticle;
import com.ruoyi.article.kafka.producer.ArticleESIndexStreamProducer;
import com.ruoyi.article.mapper.ApArticleContentMapper;
import com.ruoyi.article.mapper.ApArticleMapper;
import com.ruoyi.article.service.ApArticleService;
import com.ruoyi.article.service.ArticleFreemarkerService;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.oss.core.OssClient;
import com.ruoyi.common.oss.factory.OssFactory;
import com.ruoyi.search.domain.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {


    private final ApArticleContentMapper apArticleContentMapper;

    private final Configuration configuration;
    private final ApArticleMapper apArticleMapper;

    private final ArticleESIndexStreamProducer articleESIndexStreamProducer;

    /**
     * 生成静态文件上传到minIO中
     * @param apArticle
     * @param content
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        //已知文章的id
        //4.1 获取文章内容
        if(StringUtils.isNotBlank(content)){
            //4.2 文章内容通过freemarker生成html文件
            Template template = null;
            StringWriter out = new StringWriter();
            try {
                template = configuration.getTemplate("article.ftl");
                //数据模型
                Map<String,Object> contentDataModel = new HashMap<>();
                contentDataModel.put("content", JSONArray.parseArray(content));
                //合成
                template.process(contentDataModel,out);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //4.3 把html文件上传到minio中
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());

            OssClient storage = OssFactory.instance();
            String path = "";
            try {
                path = storage.uploadHtmlFile("", apArticle.getId() + ".html", in);
            } catch (Exception e) {
                throw new ServiceException(e.getMessage());
            }


            //4.4 修改ap_article表，保存static_url字段
            //4.把上传的staticUrl存储到article表中
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);



            //发送消息，创建索引
            SearchArticleVo vo = new SearchArticleVo();
            BeanUtils.copyProperties(apArticle,vo);
            vo.setLayout(apArticle.getLayout().intValue());

            articleESIndexStreamProducer.createArticleESIndex(vo);

        }
    }

}
